package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.crm.dto.*;
import com.jmp.autocofiguration.web.interceptor.LogOperation;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.GoodsPriceHideRequest;
import com.jmp.feign.CrmFegin;
import com.jmp.feign.GoodsFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.dto.GoodsDetailDto;
import one.stand.dto.PageResponse2;
import one.stand.mapper.GoodsApiCrmPcMapper;
import one.stand.model.GoodSpec;
import one.stand.model.Goods;
import one.stand.model.GoodsType;
import one.stand.model.ResultModel;
import one.stand.service.GoodsBaseService;
import one.stand.service.GoodsPhotoService;
import one.stand.service.GoodsTypeService;
import one.stand.service.OrderInfoBaseService;
import one.stand.util.AssertUtil;
import one.stand.util.MoneyUtil;
import one.stand.util.RequestContextHolder;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@RestController
@RequestMapping("crmPc/goods")
@Api("产品管理")
public class GoodsController {
    @Autowired
    private CrmFegin crmFegin;
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private GoodsApiCrmPcMapper goodsApiCrmPcMapper;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private OrderInfoBaseService orderInfoBaseService;

    @ApiOperation("商品选择列表")
    @PostMapping("select")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<GoodsSelectResponse> list(@RequestAttribute GoodsSelectRequest request) {

        String nameLike = SqlUtil.like(request.getName());
        PageHelper.startPage(1, 10);//默认取10个
        List<Goods> goodsModels = goodsApiCrmPcMapper.selectList(request.getCId(), nameLike);

        List<GoodsSelectResponse.Goods> goods = ConvertUtils.list(goodsModels, goodsModel -> GoodsSelectResponse.Goods.builder()
                .id(goodsModel.getGoodsId())
                .text(goodsModel.getGoodsName())
                .build()
        );

        GoodsSelectResponse response = new GoodsSelectResponse();
        response.setList(goods);
        return ResultModel.success(response);
    }

    @ApiOperation("商品列表")
    @PostMapping("list")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<GoodsListResponse> list(@RequestAttribute GoodsListRequest request) {

        String nameLike = SqlUtil.like(request.getGoodsName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> goodsList = goodsApiCrmPcMapper.selectGoods(request.getCId(), nameLike, request.getGoodstypeId(),request.getType());

        PageResponse2<GoodsListResponse.Goods> goodsPageList = ConvertUtils.page2(goodsList, goods -> {
            GoodsType goodsType = goodsTypeService.get(goods.getGoodstypeId());
            return GoodsListResponse.Goods.builder()
                    .goodsId(goods.getGoodsId())
                    .goodsName(goods.getGoodsName())
                    .goodsTypeName(goodsType.getGroupName())
                    .goodsNum(goods.getCount())
                    .price(goods.getPrice())
                    .dealNum(orderInfoBaseService.countSales(goods.getGoodsId()))
                    .createTime(goods.getCreateTime())
                    .build();
        });

        GoodsListResponse response = GoodsListResponse.builder()
                .goodsList(goodsPageList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("商品详情")
    @PostMapping("detail")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<GoodsDetailResponse> detail(@RequestAttribute GoodsDetailRequest request) {
        Goods goods = goodsBaseService.get(request.getGoodsId());
        AssertUtil.isTrue(Objects.equals(goods.getCompanyId(), request.getCId()), ResultEnum.PARAM_CHECK);

        GoodsType goodsType = goodsTypeService.get(goods.getGoodstypeId());
        List<String> goodsPhotos = goodsPhotoService.getListPath(goods.getGoodsId());

        List<GoodSpec> specs = goodsBaseService.getSpecs(goods.getGoodsId());
        List<GoodsDetailResponse.Spec> specList = Lists.newArrayList();
        int i = -1;
        for (GoodSpec spec : specs) {
            if (spec.getParentId() > 0) {
                specList.get(i).getGoodSpecModelList().add(GoodsDetailResponse.Spec.builder()
                        .specId(spec.getSpecId())
                        .specName(spec.getSpecName())
                        .specAttribute(spec.getSpecAttribute())
                        .price(Objects.nonNull(spec.getPriceRemark()) ? spec.getPriceRemark().multiply(new BigDecimal("100")).intValue() : spec.getPrice())
                        .build());
            } else {
                specList.add(GoodsDetailResponse.Spec.builder()
                        .specId(spec.getSpecId())
                        .specName(spec.getSpecName())
                        .specAttribute(spec.getSpecAttribute())
                        .goodSpecModelList(Lists.newArrayList())
                        .build());
                i++;
            }
        }

        GoodsDetailResponse goodsDetailResponse = GoodsDetailResponse.builder()
                .goodsTypeName(goodsType.getGroupName())
                .goodsName(goods.getGoodsName())
                .goodsNum(goods.getCount())
                .price(goods.getPrice())
                .contactInfo(goods.getContactInfo())
                .goodPhoto(goodsPhotos)
                .goodSpecModelList(specList)
                .build();
        return ResultModel.success(goodsDetailResponse);
    }

    @ApiOperation("商品编辑")
    @PostMapping("edit")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<GoodsEditResponse> edit(@RequestAttribute GoodsEditRequest request) {
        Goods goods = goodsBaseService.get(request.getGoodsId());
        AssertUtil.isTrue(Objects.equals(goods.getCompanyId(), request.getCId()), ResultEnum.PARAM_CHECK);

        GoodsType goodsType = goodsTypeService.get(goods.getGoodstypeId());
        List<String> goodsPhotos = goodsPhotoService.getListPath(goods.getGoodsId());

        List<GoodSpec> specs = goodsBaseService.getSpecs(goods.getGoodsId());
        List<GoodsEditResponse.Spec> specList = Lists.newArrayList();
        int i = -1;
        for (GoodSpec spec : specs) {
            if (spec.getParentId() > 0) {
                specList.get(i).getGoodSpecModelList().add(GoodsEditResponse.Spec.builder()
                        .specId(spec.getSpecId())
                        .specName(spec.getSpecName())
                        .specAttribute(spec.getSpecAttribute())
                        .price(MoneyUtil.getMoney(spec.getPrice()))
                        .specNum(spec.getSpecNum())
                        .priceBatch(spec.getPriceBatch())
                        .build());
            } else {
                specList.add(GoodsEditResponse.Spec.builder()
                        .specId(spec.getSpecId())
                        .specName(spec.getSpecName())
                        .specAttribute(spec.getSpecAttribute())
                        .goodSpecModelList(Lists.newArrayList())
                        .build());
                i++;
            }
        }

        //解析详情
        GoodsDetailDto goodsDetailDto = goodsBaseService.getDetails(goods.getGoodsDetails());

        GoodsEditResponse goodsDetailResponse = GoodsEditResponse.builder()
                .goodsTypeName(goodsType.getGroupName())
                .goodstypeId(goods.getGoodstypeId())
                .goodsName(goods.getGoodsName())
                .coverImg(goods.getCoverImg())
                .videoUrl(goods.getVideoUrl())
                .goodPhoto(goodsPhotos)
                .goodSpecModelList(specList)
                .goodsDetails(goods.getGoodsDetails())
                .goodsDetailsMemo(goodsDetailDto.getGoodsDetailsMemo())
                .goodsDetailsImgs(goodsDetailDto.getGoodsDetailsImgs())
                .showPrice(goods.getShowPrice())
                .wholesaleInfo(goods.getWholesaleInfo())
                .contactInfo(goods.getContactInfo())
                .wholesalePrice(goods.getWholesalePrice())
                .retailPrice(goods.getRetailPrice())
                .ispayment(goods.getIsPayment())
                .build();
        return ResultModel.success(goodsDetailResponse);
    }

    @ApiOperation(value = "添加/修改产品信息")
    @LogOperation(value = "保存产品信息")
    @PostMapping("/save")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel save(@RequestAttribute GoodsSaveRequest request) {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        String detail = StringUtils.isNoneBlank(request.getGoodsDetails()) ? request.getGoodsDetails()
                : goodsBaseService.getDetails(GoodsDetailDto.builder()
                .goodsDetailsMemo(request.getGoodsDetailsMemo())
                .goodsDetailsImgs(request.getGoodsDetailsImgs())
                .build());

        com.jmp.base.dto.GoodsSaveRequest saveRequest = com.jmp.base.dto.GoodsSaveRequest.builder()
                .goodsId(request.getGoodsId())
                .goodsName(request.getGoodsName())
                .goodstypeId(request.getGoodstypeId())
                .goodsDetails(detail)
                .isPayment(request.getIspayment())
                .showPrice(request.getShowPrice())
                .coverImg(request.getCoverImg())
                .videoUrl(request.getVideoUrl())
                .wholesaleInfo(request.getWholesaleInfo())
                .wholesalePrice(request.getWholesalePrice())
                .retailPrice(request.getRetailPrice())
                .goodPhoto(request.getGoodPhoto())
                .specIds(request.getSpecIds())
                .companyId(userCompanyId)
                .type(0)
                .contactInfo(request.getContactInfo())
                .build();
        return goodsFeign.save(saveRequest);
    }

    @ApiOperation(value = "添加/修改商品信息")
    @LogOperation(value = "保存商品信息")
    @PostMapping("/saveProduct")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel saveProduct(@RequestAttribute GoodsSaveRequest request) {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        com.jmp.base.dto.GoodsSaveRequest saveRequest = com.jmp.base.dto.GoodsSaveRequest.builder()
                .goodsId(request.getGoodsId())
                .goodsName(request.getGoodsName())
                .goodstypeId(request.getGoodstypeId())
                .goodsDetails(request.getGoodsDetails())
                .isPayment(request.getIspayment())
                .showPrice(request.getShowPrice())
                .coverImg(request.getCoverImg())
                .videoUrl(request.getVideoUrl())
                .wholesaleInfo(request.getWholesaleInfo())
                .goodPhoto(request.getGoodPhoto())
                .specIds(request.getSpecIds())
                .companyId(userCompanyId)
                .type(1)
                .contactInfo(request.getContactInfo())
                .build();
        return goodsFeign.save(saveRequest);
    }


    @ApiOperation("该企业所有产品价格隐藏")
    @PostMapping("price/hide")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel priceHide() {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        GoodsPriceHideRequest priceHideRequest = GoodsPriceHideRequest.builder()
                .companyId(userCompanyId)
                .build();
        goodsFeign.priceHide(priceHideRequest);

        return ResultModel.success();
    }

    @ApiOperation("该企业所有产品价格显示")
    @PostMapping("price/show")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel priceShow() {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        GoodsPriceHideRequest priceHideRequest = GoodsPriceHideRequest.builder()
                .companyId(userCompanyId)
                .build();
        goodsFeign.priceShow(priceHideRequest);

        return ResultModel.success();
    }
}
